package cn.hd.controller;

import cn.hd.entity.Bill;
import cn.hd.entity.Productdetail;
import cn.hd.entity.Result;
import cn.hd.service.BillService;
import cn.hd.service.ProductdetailService;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
@CrossOrigin
@RestController
public class PayController {
    @Autowired
    private BillService billService;
    @Autowired
    private ProductdetailService productdetailService;
    // 应用的APPID
    private final String APP_ID = "2021000118667228";
    // 生成的应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDglDptZJwp/QtbpTRHrIk8qo4tyy6zRI/Ppa3DVb5srqi1B9x899a4ifkwjcgnCAUJAdTwIkqVzRQrm2sGwlzhKrdkT+XL6AjLD89gjgwlPudKQhzJqP5FEvw8kNPEpBpdnhq0xLn5Bz3/REOyn4PeeDhTqiQGc26/YoGh0VorsOPdlSsm0xi6Hcpvshfc8aw5BtrgZoCcqV8p4Vd4PW4noR3km5KFZnlGMlbItw1+cHWINFb3duHtRV3Rv9Z0WY5z3w400kHZXw6uKrdJ7rcamZArisZzy4K5A/gvuKqgxp6EOcoDnQ/vI5im4srtOzIe2/3n8TsKSPW7m3BcCd0nAgMBAAECggEAVNpswQx0nMDJW9Utza75I3zlv5O3j3BmTfSxlM5+5p2PjObtfiI+dPdcueW4LFcxX9fbVuf9+l/EMT3F0IX7hfAX3sT5dHO1btQIbNj+6cu8pCgarG83s22a9F9cRD4k4B5uxMJX6im8WQi383Ol5Z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HARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhM8LHdniCAOLiQVqgjrrR3szX2QopeMSzmT8IkvTCnuly9Qgq5D3///ToNQ/BvmpSj4SOsaArDBXmISyUoj5ucpCqVgYF/V464RrJMt9ewtsSQm1XVsm+3J5Vk0g5LUvTAmeP/ecDVohzY+3skcbosU5krnSq3iguijo8r2sHoJNnOT7saDqM4MxDShwOly97Iut3Wbisn+slflv6RC+TAIJal+dGN8PMDV7K5c0OlduN9hfH3IveelHuwFcOEHxq9zyBN38Lnct+uaIFpG7X966RXJP4oOFzQjmPyWTmwgR/plnexvk0JmOU79C06y2tVWhAqWZHyVg9Fob/BtgbwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/success";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/#/order3";

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public Object returnUrl(String uuid,HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("==============同步回调==============");

        System.out.println(uuid);

        //支付完成后更改支付状态
//        orderService.updatePayment(order.getOid());
        billService.updateDDZT(uuid);
        Bill bill = billService.selectDDByuuid(uuid);
        //支付完成后增加支持人数
        productdetailService.updateZCjia1(bill.getProductname());
        //支付完成后增加金额
        productdetailService.updatselectPricenumBypnaem(bill.getProductname(),bill.getPrice());
        return new Result("203","支付成功！",bill);
//        // 获取支付宝GET过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map<String, String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i] :
//                        valueStr + values[i] + ",";
//            }
//            // 乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
//            params.put(name, valueStr);
//        }
//
//        System.out.println(params);//查看参数都有哪些
//        boolean signVerified = AlipaySignature.
//                rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
//        //调用service中的方法来改变订单的付款状态
//        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//        if (signVerified){
//            billService.updateDDZT(out_trade_no);
//            return "成功";
//        }else {
//            billService.updateDDZTWZF(out_trade_no);
//            return "未支付";
//        }
        //验证签名通过
//        if(signVerified){
//            // 商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//            // 支付宝交易号
//            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//            // 付款金额
//            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
//
//            System.out.println("商户订单号="+out_trade_no);
//            System.out.println("支付宝交易号="+trade_no);
//            System.out.println("付款金额="+total_amount);
//
//            //支付成功，调用自己的业务去修改支付状态
//            // ---------------------------------------------------
//            //payService.updateById(Integer.valueOf(out_trade_no));
//            // ---------------------------------------------------
//            return "()";   //跳转付款成功页面
//        }else{
//            return "error.html";  //跳转付款失败页面
//        }

    }

    @RequestMapping("/alipay")
    @ResponseBody
    public Object alipay(HttpServletResponse httpResponse,Integer bid) throws IOException {

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        Bill bill = billService.selectBillByBid(bid);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        // 测试中数据随机产生，开发中调用项目中的真实数据即可
        //生成随机Id
        String out_trade_no = bill.getUuid();
        //付款金额，必填
        String total_amount =Double.toString(bill.getPrice());
        //订单名称，必填
        String subject =bill.getProductname();
        //商品描述，可空
        Productdetail productdetail = productdetailService.selectAllByXiamgMuname(bill.getProductname());
        String body = productdetail.getPdesc();
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
        return new Result("200","跳到支付页面",form);
    }
}

